package com.cash.app.ui.main.fg.repay

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.cash.app.base.BaseViewModel
import com.cash.app.constant.AppConstant
import com.cash.app.constant.AppConstant.TYPE_LOAN_LIST_REPAY
import com.cash.app.manager.api.GlobalAPIService
import com.cash.app.manager.model.LoanDataResponse
import com.cash.app.manager.model.LoanListRequest
import com.cash.app.manager.model.OrderIdRequest
import com.cash.app.manager.model.RepayResponse
import com.cash.app.net.NetRequestExecutor
import com.cash.app.net.RetrofitClient
import com.cash.app.utils.SpUtils
import com.cash.app.utils.TLog

class RepayViewModel : BaseViewModel() {

    private val apiService = RetrofitClient.createService(GlobalAPIService::class.java)

    private val globalAPIService by lazy {
        RetrofitClient.createService(GlobalAPIService::class.java)
    }

    private val _repayData = MutableLiveData<LoanDataResponse>()
    val repayData: LiveData<LoanDataResponse> = _repayData

    private val _showEmptyState = MutableLiveData<Boolean>()
    val showEmptyState: LiveData<Boolean> = _showEmptyState

    private val _repayInfoLiveData = MutableLiveData<RepayResponse>()
    val repayInfo: LiveData<RepayResponse> = _repayInfoLiveData

    fun getRepayList() {
        if (!SpUtils.get(AppConstant.K_APP_LOGIN, false)) {
            TLog.d("getRepayList need login", "RepayViewModel")
            _showEmptyState.value = true
            return
        }
        launchRequest(request = {
            NetRequestExecutor.baseNetRequest {
                apiService.getLoanList(
                    LoanListRequest(
                        list_type = TYPE_LOAN_LIST_REPAY
                    )
                )
            }
        }, onSuccess = { response ->
            response?.let {
                _showEmptyState.value = it.order_list.isEmpty()
                _repayData.value = it
            }
        }, onError = { _, _ ->
            _showEmptyState.value = true
        })
    }

    fun getRepayUrl(orderId: Int) {
        launchRequest(request = {
            NetRequestExecutor.baseNetRequest {
                globalAPIService.getRepayUrl(OrderIdRequest(orderId))
            }
        }, onSuccess = { response ->
            response?.let {
                _repayInfoLiveData.value = it
            }
        })
    }
}